import {Component, OnInit} from '@angular/core';
import {ListBasicItem, UserInfo} from "../../modals/basic.modal";
import {ActivatedRoute, Router} from "@angular/router";
import {AlertComponent} from "../../unit/alert";
import {BasicService} from "../../unit/basic-service";
import {Photo, PhotoService} from "../../services/photo.service";
import {environment} from "../../../environments/environment";

@Component({
    selector: 'app-user',
    templateUrl: './user.page.html',
    styleUrls: ['./user.page.scss'],
})
export class UserPage implements OnInit {
    userData: UserInfo;
    confirmPassword: string;
    showLoginModal: boolean;
    initNumber = 0;
    currentVersion = '1.0';
    servicePhone = '';
    avatarImg: string;
    photoList: Photo[] = [];
    saveLoading: boolean;
    constructor(
        private route: Router,
        private alertComponent: AlertComponent,
        private activateInfo: ActivatedRoute,
        private basicService: BasicService,
        public photoService: PhotoService,
    ) {
    }

    ngOnInit() {
        this.reGroupUserData();
        this.initBasicList();
        this.getAvatar();
        this.activateInfo.queryParamMap.subscribe((res: any) => {
        });
    }

    getAvatar() {
        this.avatarImg = '';
        this.basicService.getData('appPortrait/get').subscribe(res => {
            this.setAvatar(res);
        })
    }

    setAvatar(data) {
        const token = localStorage.getItem('medicalToken');
        this.avatarImg = data.tx ? `${environment.basicUrl}/uploadappPortrait/${data.tx}?access_token=${token}` : './assets/image/user/avatar.jpeg';
    }

    changeAvatar() {
        this.photoService.addNewToGallery('', this.updateImage.bind(this)).then();
    }

    updateImage(event) {
        this.photoList[0] = event;

        const currentFile = this.photoList[0];
        const formData = new FormData();

        formData.append('files', currentFile.filepath);
        formData.append('fileType', currentFile.fileType);

        this.basicService.postSingleFile('file/uploadAppPortrait', formData).subscribe((res: any) => {
            if (res && res.code === 0) {
                this.getAvatar();
                this.alertComponent.presentAlert('上传成功！').then();
            }
            this.saveLoading = false;
        });
    }

    initBasicList() {
        this.basicService.getData('users/currentUser').subscribe(res => {
            this.reGroupUserData(res);
        })
    }

    reGroupUserData(data: any = null) {
        if (data) {
            const {realName, createdDate, kfdh, bbh, sfrz} = data;
            this.userData = {
                name: realName,
                avatar: '代用名',
                isAuthentication: sfrz,
                creationTime: createdDate,
            };

            this.servicePhone = kfdh;
            this.currentVersion = bbh;
        } else {
            this.userData = {
                name: '',
                avatar: '',
                isAuthentication: '',
                creationTime: '',
            };

            this.servicePhone = '';
            this.currentVersion = '';
        }

    }

    showDetail(item) {
        if (item.url) {
            this.goToPage(item.url);
        }
    }

    closeLoginModal(e) {
        this.showLoginModal = false;
        if (!e) {
            // login faild
            this.goToPage('tabs');
        } else {
            this.goToPage('tabs/main');
        }
    }

    goToPage(url, item = {}) {
        this.route.navigate([`/${url}`], {queryParams: {...item}}).then();
    }

}
